<?php

/* 
 * 商品测试
 * @author wyb
 */
namespace Api\Api\Pay;
class Pay extends \Api\Api\Base{
    
    /**
     * 支付接口
     * @param [type] $data [description]
     */
    public function Pay( $data ) {
    	//订单数据效验
    	$result = $this->_checkOrder( $data );
    	if( $result === false ) return false;

        //获得商家code
        $data['channel_code'] = M('customer')->where(array('id' => $data['app_id']))->getField('code');
    	//订单入库
    	$data = $this->_addOrder( $data );
    	if( $data === false ) return false;

    	//数据合并
    	$data = array_merge( $data , $result );
    	$data['product_total'] += $data['product_total_fee'];

    	//前端数据显示组合
    	$contect_info = explode('|' , $data['receive_info'] );
    	$data['mobile'] = $contect_info[1];
    	unset( $contect_info[1] );
    	unset( $contect_info[0] );
    	$data['address'] = implode('',$contect_info);
    	
    	//获得商品图片
    	foreach( $data['order_line'] as $key => $value ) {
    		$data['order_line'][$key]['thumb'] = M('goods')->where(array('sku' => $value['sku']))->getField( 'pic_thumb' );
    	}

    	$data['request_url'] = \Api\Server\PaymentServer::init()->aign( array( 'id' => $data['order_id'] ) );
    	return $data;
    }
    
    /**
     * 退款
     */
    public function Refund( $data ) {
        $customer_code = M('customer')->where(array('id' => $data['app_id']))->find();
        $order_data = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')
                                            ->where( array( 'o.ref' => $data['ref'] , 'o.state' => 1 ) )
                                            ->field('o.id,o.channel_code,op.payment_no,op.payment_account AS pay_type,o.ref,o.ref_extend,o.amount_total')
                                            ->find();
        if( !$order_data ) {
            $this->_error = '退款订单不存在';
            return false;
        }
        if( !$order_data['channel_code'] || $order_data['channel_code'] != $customer_code['code'] ) {
            $this->_error = '订单不存在';
            return false;
        }
        if( $order_data['amount_total'] < $data['price'] ) {
            $this->_error = '退款金额不对';
            return false;
        }
        
        //通知地址入库
        M('order')->where(array('ref' => $data['ref']))->save(array('refund_notify_url' => $data['notify_url']));

        $pay_config = '';

        //获得配置
        $pay_config = D('Common/PaymentConfig')->getSettingConfig( $order_data['id'] , $order_data['pay_type'] );

        if( !$pay_config ) {
            $this->_error = '支付不存在，请联系平台客服处理。';
            return false;
        }

        $object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $order_data['pay_type'] ); //组合空间命名
        $object = new $object_name( $pay_config );

        $result = $object->orderRefund( $order_data , $data['price'] );
        if( $result['status'] === true ) {
            M('order')->where(array('ref' => $data['ref']))->save(array('state' => 4)); //订单已退款
            return true;
        } else {
            $this->_error = $result['msg'];
            return false;
        }
    }

    /**
     * 订单入库
     * @param  array $[name] [<description>]
     */
    private function _addOrder( $data ) {
    	//判断订单是否已存在，如果存在则替换订单里面的数据
    	$order_model = M('order');
        $data['ref_extend'] = rand(100,999);
    	$order_line_model = M('order_line');
    	if( $order_data = $order_model->where(array('ref' => $data['ref']))->find() ) {
            if( $order_data['state'] == 1 ) {
                $this->_error = '订单已支付，请勿重复支付';
                return false;
            }
            $data['id'] = $order_data['id'];
            //删除商品信息
            $order_line_model->where(array('order_id' => $order_data['id']))->delete();
            //修改订单信息
            if( $order_model->create( $data ) === false ) {
                    $this->_error = '信息错误';
                    return false;
            }
            //更新
            if( $order_model->save() === false ) {
                    $this->_error = '信息错误';
                    return false;
            }
            $data['order_id'] = $data['id'];
    	} else {
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['erp_order_sync'] = 0;
            $data['wx_order_sync'] = 0;
            $data['state'] = 0;
    		//增加订单信息
    		if( $order_model->create( $data ) === false ) {
    			$this->_error = '信息错误';
    			return false;
    		}
    		//增加
    		$data['order_id'] = $order_model->add();
    		if( $data['order_id'] === false ) {
    			$this->_error = '信息错误';
    			return false;
    		}
    	}

    	//增加商品信息
    	foreach( $data['order_line'] as $key => $value ) {
    		$data['order_line'][$key]['ref'] = $data['ref'];
    		$data['order_line'][$key]['order_id'] = $data['order_id'];
    		$data['order_line'][$key]['create_time'] = date('Y-m-d H:i:s');
    		$data['order_line'][$key]['date_order'] = $data['date_order'] ? $data['date_order'] : date('Y-m-d H:i:s');
    	}
        if( $order_line_model->addAll( $data['order_line'] ) === false ) {
                $this->_error = '信息错误';
                return false;
        }
        return $data;
    }

    /**
     * 商品数据认证
     * @param  array $goods_data 商品数据列表
     */
    private function _checkGoods( $goods_data ) {
    	$data = array();
    	foreach( $goods_data  as $key => $value ) {
    		//验证商品是否存在
    		if( !M('goods')->where(array('sku' => $value['sku']))->find() ) {
    			$this->_error = "未查询到SKU【{$value['sku']}】的商品，请核对。";
    			return false;
    		}

    		//验证金额是否相等
    		if( $value['sub_total'] - ( $value['price'] * $value['num'] + $value['tax_fee'] ) != 0  ) {
    			$this->_error = "SKU【{$value['sku']}】的商品价格有误，请核对。";
    			return false;
    		}

    		//商品税认证
    		$data['product_total'] += $value['sub_total_untaxed'];//商品总价
    		$data['product_total_fee'] += $value['tax_fee']; //商品税
    	}

    	return $data;
    }

    /**
     * 订单数据效验
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function _checkOrder( $data ) {
    	//身份证数据认证
    	if( $data['buyer_id_card'] && $data['buyer_id_type'] == 1 && !preg_match( '/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/i' , $data['buyer_id_card'] ) ) {
    		$this->_error = "身份证信息效验失败";
    		return false;
    	}
    	//商品效验
    	$result = $this->_checkGoods( $data['order_line'] );
    	if( $result === false ) return false;

    	//商品总价格效验
    	if( $data['amount_untaxed'] != $result['product_total'] ) {
    		$this->_error = "商品总价格有误";
    		return false;
    	}
    	//订单总价格效验
    	$ckeck_goods_price = $data['amount_total'] - $data['delivery_fee'] - array_sum( $result );
    	if( $ckeck_goods_price > 1 || $ckeck_goods_price < -1  ) {
    		$this->_error = "订单总金额数据有异常";
    		return false;
    	}
    	return $result;
    }
}